<!-- 权限管理-部门管理 -->
<template>
  <div class="app-container">
    <!-- 头部增删区域 -->
    <div class="search_and_new">
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="addGrade">添加子部门</el-button>
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="addGrade2">添加一级部门</el-button>
      <el-button type="danger" size="mini" icon="el-icon-close" @click="delGrade">批量删除</el-button>
      <el-button type="info" size="mini" icon="el-icon-refresh" @click="department_getByParentId">刷新</el-button>
    </div>
    <!-- 树状区域 -->
    <el-row :gutter="100">
      <el-col :span="6">
        <div class="selected_tree">
          <span class="el-icon-info" />
          <span>当前选择编辑：</span>
          <span style="font-weight:600;color:#40a9ff;">{{ selectedTree.title }}</span>
          <span v-show="selectedTree != ''" style="color:#2d8cf0;padding-left:5px;cursor:pointer;" @click="deselect_tree">取消选择</span>
        </div>
        <el-tree
          ref="tree"
          :data="departments"
          show-checkbox
          default-expand-all
          node-key="id"
          highlight-current
          :check-strictly="true"
          :props="defaultProps"
          @node-click="click_tree"
          @check-change="click_check()"
        />
      </el-col>
      <el-col :span="10">
        <el-form ref="department_form" :rules="rules" :model="department_form" label-width="90px" size="mini" style="width:350px;">
          <el-form-item class="form_sj" label="上级部门" prop="grade">
            <el-input v-model="department_form.grade" readonly="readonly" style="width:156px;" />
            <el-popover placement="right" width="400" trigger="click">
              <div style="font-size:15px; color:#666;height:30px;border-bottom:solid 1px #eee;margin-bottom:5px;">请选择上级部门：</div>
              <el-tree
                ref="tree2"
                :data="departments"
                default-expand-all
                node-key="id"
                highlight-current
                :props="defaultProps"
                @node-click="click_tree2"
              />
              <el-button slot="reference" type="primary" icon="el-icon-plus" :disabled="selectedTree == ''">选择部门</el-button>
            </el-popover>
          </el-form-item>
          <el-form-item label="部门名称" prop="title">
            <el-input v-model="department_form.title" />
          </el-form-item>
          <el-form-item label="部门负责人">
            <el-select v-model="department_form.value" multiple placeholder="请选择" style="width:260px;">
              <el-option v-for="item in department_form.mainHeader" :key="item.id" :label="item.username" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="副负责人" prop="viceHeader">
            <el-select v-model="department_form.deputy_value" placeholder="请选择" multiple style="width:260px;">
              <el-option v-for="item in department_form.viceHeader" :key="item.id" :label="item.username" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number v-model="department_form.sortOrder" :min="1" />
          </el-form-item>
          <el-form-item label="是否启用" prop="status">
            <el-switch v-model="department_form.status" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="edit('department_form')">修改并保存</el-button>
            <el-button type="info" @click="resetForm('department_form')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 弹出区域--添加子部门 -->
    <el-dialog
      title="添加子部门"
      :visible.sync="branchDialog"
      :close-on-click-modal="false"
      :before-close="handleClose"
      width="25%"
    >
      <el-form ref="grade_form2" :rules="rules" :model="grade_form2" label-width="90px" size="mini">
        <el-form-item label="上级部门" prop="grade">
          <el-input v-model="grade_form2.grade" readonly="readonly" />
        </el-form-item>
        <el-form-item label="部门名称" prop="title">
          <el-input v-model="grade_form2.title" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="grade_form2.sortOrder" :min="1" />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="grade_form2.status" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleClose">取消</el-button>
        <el-button type="primary" size="mini" @click="grade_preserve2('grade_form2')">提交</el-button>
      </div>
    </el-dialog>
    <!-- 弹出区域--添加一级部门 -->
    <el-dialog
      title="添加一级部门"
      :visible.sync="branchDialog2"
      :close-on-click-modal="false"
      :before-close="handleClose"
      width="25%"
    >
      <el-form ref="grade_form" :rules="rules" :model="grade_form" label-width="90px" size="mini">
        <el-form-item label="部门名称" prop="title">
          <el-input v-model="grade_form.title" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="grade_form.sortOrder" :min="1" />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="grade_form.status" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleClose">取消</el-button>
        <el-button type="primary" size="mini" @click="grade_preserve('grade_form')">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      branchDialog: false, // 添加子部门 状态
      branchDialog2: false, // 添加一级部门 状态
      grade_form: { // 添加一级部门
        title: '', // 部门名称
        sortOrder: 1, // 排序
        status: true // 是否启用
      },
      grade_form2: { // 添加子级部门
        grade: '', // 上一级部门
        title: '', // 部门名称
        sortOrder: 1, // 排序
        status: true // 是否启用
      },
      departments: [
        // 树状数据
      ],
      defaultProps: {
        // 树状类型
        children: 'childrenDepartment',
        label: 'title'
      },
      department_form: {
        grade: '', // 上一级部门
        title: '', // 部门名称
        sortOrder: 1, // 排序
        status: true, // 是否启用
        mainHeader: [
          // 部门负责人 选项
        ],
        value: '', // 部门负责人 绑定值
        viceHeader: [
          // 副负责人 选项
        ],
        deputy_value: '' // 副负责人 绑定值
      },
      rules: {
        title: [{
          required: true,
          message: '请输入部门名称',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 10,
          message: '长度在 2 到 10 个字符',
          trigger: 'blur'
        }
        ],
        sortOrder: [{
          required: true,
          message: '请输入排序',
          trigger: 'blur'
        }],
        grade: [],
        options: [],
        value: [],
        deputy_value: []
      },
      getCheckedNodes: [], // 当前节点被选中的集合
      selectedTree: '' // 当前选择编辑
    }
  },
  created() {
    this.department_getByParentId()
  },
  methods: {
    // 渲染树形图
    department_getByParentId() {
      this.$Http.department_getByParentId().then(res => {
        if (res.code === 200) {
          this.departments = res.result
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    // 选中当前节点（对勾）
    click_check() {
      this.getCheckedNodes.length = 0
      this.$refs.tree.getCheckedNodes().forEach((item) => {
        this.getCheckedNodes.push(item.id)
      })
    },
    // 选中树状节点
    click_tree(item, e) {
      // 当参数为两个的时候，第一个是自身节点，第二个是父节点
      this.department_form.mainHeader = []
      this.department_form.viceHeader = []
      this.selectedTree = item
      if (e.parent.data.title === undefined) {
        this.department_form.grade = '顶级节点'
      } else {
        this.department_form.grade = e.parent.data.title
      }
      this.department_form.title = this.selectedTree.title
      this.department_form.sortOrder = this.selectedTree.sortOrder
      if (this.selectedTree.status === '-1') {
        this.department_form.status = false
      } else {
        this.department_form.status = true
      }
      this.department_form.data = this.selectedTree
      this.department_form.value = this.selectedTree.mainHeader
      this.department_form.deputy_value = this.selectedTree.viceHeader
      // 点击节点 获取节点下的部门负责人
      this.$Http.department_getByDepartmentId({
        departmentId: this.selectedTree.id
      }).then(res => {
        console.log(res.result)
        if (res.result.length >= 1) {
          this.department_form.mainHeader = res.result
          this.department_form.viceHeader = res.result
        }
      })
    },
    click_tree2(e) {
      if (this.department_form.grade === '顶级节点') {
        this.department_form.grade = '顶级节点'
        this.department_form.data.parentId = '0'
      } else {
        this.department_form.data.parentId = e.id
        this.department_form.grade = e.title
      }
    },
    // 点击取消选择
    deselect_tree() {
      this.selectedTree = ''
      this.department_form = {}
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.department_form.data = {}
    },
    // 添加子部门
    addGrade(e) {
      if (this.selectedTree === '') {
        this.$message.error('请选择一个部门！')
      } else {
        this.branchDialog = true
        this.grade_form2.grade = this.selectedTree.title
      }
    },
    // 添加一级部门
    addGrade2(e) {
      this.branchDialog2 = true
    },
    // 添加子部门 确认按钮
    grade_preserve2(notEmpty) {
      this.$refs[notEmpty].validate(valid => {
        if (valid) {
          const data = this.grade_form2
          data.parentId = this.selectedTree.id
          delete data.grade
          if (data.status) {
            data.status = 0
          } else {
            data.status = -1
          }
          this.$Http.department_add(data).then(res => {
            this.department_getByParentId()
          })
          this.branchDialog = false
          this.resetForm('grade_form2') // 回调成功 重置表单
        } else {
          return false
        }
      })
    },
    // 添加一级部门 确认按钮
    grade_preserve(notEmpty) {
      this.$refs[notEmpty].validate(valid => {
        if (valid) {
          const data = this.grade_form
          data.parentId = 0
          delete data.grade
          if (data.status) {
            data.status = 0
          } else {
            data.status = -1
          }
          this.$Http.department_add(data).then(res => {
            this.department_getByParentId()
          })
          this.branchDialog2 = false
          this.resetForm('grade_form') // 回调成功 重置表单
        } else {
          return false
        }
      })
    },
    // 批量删除
    delGrade() {
      if (this.getCheckedNodes.length < 1) {
        return this.$message.error('请选择要删除的部门！')
      }
      this.$confirm('此操作将永久删除该部门以及当前部门下的所有子部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        console.log(res)
        this.getCheckedNodes = Array.from(new Set(this.getCheckedNodes))
        this.$Http.department_del2(this.getCheckedNodes).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.department_getByParentId()
          } else {
            this.$message({
              type: 'erroe',
              message: res.message
            })
          }
        }).catch((error) => {
          console.log('err', error)
        })
      }).catch((res) => {
        console.log(res)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 提交修改 并保存
    edit(notEmpty) {
      if (!this.department_form.data) {
        return this.$message({
          message: '请选择要修改的部门',
          type: 'warning'
        })
      }
      this.$refs[notEmpty].validate(valid => {
        if (valid) {
          var data = []
          this.department_form
          data.title = this.department_form.title
          data.sortOrder = this.department_form.sortOrder
          data.mainHeader = this.department_form.value
          data.viceHeader = this.department_form.deputy_value
          data.parentId = this.department_form.data.parentId
          data.id = this.department_form.data.id
          if (this.department_form.status === true) {
            data.status = 0
          } else {
            data.status = -1
          }
          console.log(data)
          this.$Http.department_edit(data).then(res => {
            // this.department_getByParentId()
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
          })
          // this.resetForm(notEmpty) // 回调成功 重置表单
          // this.department_form.data = {}
        } else {
          return false
        }
      })
    },
    // 取消弹窗
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.branchDialog = false
          this.branchDialog2 = false
        })
        .catch(_ => {})
    }
  }
}
</script>
<style lang="scss" scoped>
  .app-container {
    padding: 0;
    margin: 20px;
  }

  .search_and_new {
    height: 5vh;
  }

  .search_and_new>div {
    display: inline-block;
    margin-right: 15px;
  }

  .paging_device {
    margin-top: 20px;
  }

  .selected_tree {
    border: solid 1px #abdcff;
    background: #f0faff;
    border-radius: 4px;
    color: #515a6e;
    font-size: 14px;
    line-height: 32px;
    margin-bottom: 10px;
    height: 32px;
    text-align: left;
    padding: 0 15px;

    span.el-icon-info {
      color: #2d8cf0;
      padding-right: 5px;
    }
  }
</style>
